import { SerialPort } from "serialport";
import { BrowserWindow } from "electron";
import { IsignaLightStatus } from "./C300ProtocolHandler";
interface SerialPortOptions {
  path: string;
  baudRate?: number;
  dataBits?: 8 | 5 | 6 | 7 | undefined; // 数据位
  parity?: "none" | "even" | "odd" | "mark" | "space"; // 校验位
  stopBits?: 1 | 1.5 | 2 | undefined; // 停止位
}

export interface IDregister {
  dataStr: string;
  dataBuf: Buffer<ArrayBuffer>;
  dataUint16: number[];
  dataUint32?: number[];
}

export class SerialPortReader {
  private port: SerialPort;
  //public recvBuf: Buffer<ArrayBuffer> = Buffer.alloc(0);
  //private recvStart: boolean = false;
  constructor(options: SerialPortOptions) {
    const {
      path,
      baudRate = 9600,
      dataBits = 7,
      parity = "even",
      stopBits = 1,
    } = options;
    this.port = new SerialPort({
      path,
      baudRate,
      dataBits,
      parity,
      stopBits,
      autoOpen: false, // 先不打开，稍后手动打开
    });

    // 监听错误事件
    this.port.on("error", (err) => {
      console.error("Serial Port Error:", err.message);
    });

    // 监听数据接收
    this.port.on("data", (data: Buffer<ArrayBuffer>) => {
      this.onDataReceived(data);
    });
  }

  // 打开串口
  public open(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.port.open((err) => {
        if (err) {
          return reject(err);
        }
        console.log("Serial Port Opened:", this.port.path);
        resolve();
      });
    });
  }

  // 关闭串口
  public close(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.port.close((err) => {
        if (err) {
          return reject(err);
        }
        console.log("Serial Port Closed");
        resolve();
      });
    });
  }

  public send(data) {
    this.port.write(data);
  }
  // 处理接收到的数据
  protected onDataReceived(data: Buffer): void {
    console.log("Received data:", data);
    // 这里可以添加对数据的进一步处理
  }
}


/* 04C10DB7 */
//02 45 30 30  34 30 30 30  30 34  03 44 30   d0
//   45 31 30  34 30 30 30  30 32  30 35 30 30   03 34 43
//02 45 30 30  30 30 30 30  30 31  03 43 39
//02 45 31 30  34 30 30 30  30 32  30 35 30 30   03 39 34 写D0  5
//02 45 31 30  34 30 30 30  30 34  30 35 30 30  30 30 30 30  03 35 36  写D0  5  32位
//02 45 31 30  34 30 30 30  30 34  30 35 30 30  30 30 30 30  03 35 36

/* (async () => {
  

  /* setInterval(async () => {
    console.log(await serial.readBitsData(0, 4));
  }, 500);
  serial.wirteMbit(118, false);
  /* await serial.wirteUint16register(0, [5]);
  await serial.wirteUint32register(0, [5]); 
})();
 */